package com.example.jf.jfapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.example.jf.jfapp.activity.base.BaseMultipleStatuActivity;
import com.example.jf.jfapp.adapter.SquareAdapter;
import com.example.jf.jfapp.bean.bean.PariseRequestBean;
import com.example.jf.jfapp.bean.request.DongTaiListRequest;
import com.example.jf.jfapp.bean.request.StatuRequest;
import com.example.jf.jfapp.bean.request.UpdateLocationRequest;
import com.example.jf.jfapp.bean.response.DongTaiSquareResponse;
import com.example.jf.jfapp.receiver.CommentReceiver;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.BaiDuLocationUtils;
import com.example.jf.jfapp.utils.Constant;
import com.example.jf.jfapp.utils.OkHttpUtils;
import com.example.jf.jfapp.utils.OperationUtils;
import com.example.jf.jfapp.utils.RequestUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DongTaiSquareActivity extends BaseMultipleStatuActivity {
    /**
     * 启动发送动态界面的CODE
     */
    private static final int START_SEND_STATU_CODE = 111;
    /**
     * 点赞是否真正运行中，点击点赞按钮后修改值为false
     */
    protected boolean pariseING = true;
    private StatuRequest mStatusRequest;

    public StatuRequest mStatuRequest;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private DongTaiListRequest mdongTaiListRequest;  //状态列表数据
    private List<DongTaiSquareResponse.ResultBean> mlists = new ArrayList<>();


    private static final String TAG = "DongTaiSquareActivity";
    @BindView(R.id.publish)
    ImageView publish;
    @BindView(R.id.rv)
    RecyclerView rv;
    SquareAdapter sadapter;

    //从后台固定获取到10条数据
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dong_tai_square);
        ButterKnife.bind(this);
        initView();
        getStatuData(true);
        initLocation();
    }

    @Override
    public void initView() {
        rv=(RecyclerView)findViewById(R.id.rv);

        initRefreshLayout();


        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("");


        mStatuRequest = new StatuRequest(3);
        //获取用户信息
        mStatuRequest.setUserId(AppConfigUtils.getInstance().getLoginInfo(this).getObjectId());

        rv.setLayoutManager(new LinearLayoutManager(this));
        sadapter = new SquareAdapter(mlists,this);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(sadapter);


        //设置点击事件
        sadapter.setmClickListener(new SquareAdapter.ActionClickListener() {
           //点击评论窗口
            @Override
            public void commentClick(DongTaiSquareResponse.ResultBean resultBean, int position) {
                Intent intent = new Intent(DongTaiSquareActivity.this, CommentActivity.class);
                intent.putExtra(CommentActivity.STATU_ID_KEY, resultBean.getStatuId());
                startActivity(intent);
            }

            @Override
            public void pariseClick(DongTaiSquareResponse.ResultBean resultBean, int position) {
                parise(resultBean, position);
            }

            @Override
            public void headClick(DongTaiSquareResponse.ResultBean resultBean, int position) {

            }

            @Override
            public void contentClick(DongTaiSquareResponse.ResultBean resultBean, int position) {
                getlog();
                }
        });




        //添加分割线
        rv.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        rv.setAdapter(sadapter);

        registerCommentReceiver();
    }
    private void  getlog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage("应用功能没实现？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
    @Override
        public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
       finish();
        }
        });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {


                @Override
                public void onClick(DialogInterface dialog, int i) {
                    dialog.dismiss();
                }
            });
    builder.create().show();

    }
    /**
     * 点赞
     *
     * @param resultBean
     * @param position
     */
    public void parise(final DongTaiSquareResponse.ResultBean resultBean, final int position) {
        if (pariseING) {
            pariseING = false;
            PariseRequestBean mRequestBean = new PariseRequestBean();
            mRequestBean.setStatusId(resultBean.getStatuId());
            mRequestBean.setUserId(AppConfigUtils.getInstance().getLoginInfo(this).getObjectId());
            OperationUtils.parise(mRequestBean, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pariseING = true;
                            //取得之前的状态
                            if (resultBean.isPraiseStatus()) {
                                Toast.makeText(DongTaiSquareActivity.this, "取消失败", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(DongTaiSquareActivity.this, "点赞失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pariseING = true;
                            //取得点赞个数，取消则-1
                            int pariseSize = mlists.get(position).getPraiseSize();
                            //判断之前的状态，然后设置点击之后的状态，这里直接本地处理，避免再次请求网络数据
                            if (mlists.get(position).isPraiseStatus()) {//如果之前状态为点赞，那么点击后是取消
                                mlists.get(position).setPraiseSize(pariseSize - 1);
                                mlists.get(position).setPraiseStatus(false);
                                Toast.makeText(DongTaiSquareActivity.this, "取消成功", Toast.LENGTH_SHORT).show();
                            } else {
                                mlists.get(position).setPraiseSize(pariseSize + 1);
                                mlists.get(position).setPraiseStatus(true);
                                Toast.makeText(DongTaiSquareActivity.this, "点赞成功", Toast.LENGTH_SHORT).show();
                            }
                            sadapter.notifyItemChanged(position);
                        }
                    });
                }
            });
        }
    }

    private void initRefreshLayout() {
        RefreshLayout refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //刷新的监听
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);

                mStatuRequest.setTimestamp(0);
                getStatuData(true);
            }
        });

        //加载更多的监听
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                Log.e(TAG, "onLoadmore: 加载更多");
                refreshlayout.finishLoadmore(2000);
                getStatuData(false);

            }
        });
    }


    /**
     * 获取状态数据
     */

    public void getStatuData(final boolean isRefresh) {//记录当前请求的类型， true 刷新   false 加载更多
        final Request request = RequestUtils.requestPOST(mStatuRequest, Constant.URL.GETSTATUS);
        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showErrorView();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    String result = response.body().string();
                    Log.e(TAG, "onResponse: " + result);
                    if (result != null) {
                        DongTaiSquareResponse dongListArray = new Gson().fromJson(result, DongTaiSquareResponse.class);
                        if (isRefresh) {//区分当前请求的类型
                            refreshData(dongListArray);
                        }

                            else {
                            loadMore(dongListArray);
                        }
                    } else {
                        showEmptyView();
                    }
                } else {
                    showErrorView();
                }
            }
        });
    }

    //刷新
    public void refreshData(DongTaiSquareResponse dongListArray) {
        mlists.clear();
        for (int i = 0; i <dongListArray.getResult().size(); i++) {
            mlists.add(dongListArray.getResult().get(i));
        }


        //主动设置请求参数的时间戳
        mStatuRequest.setTimestamp(mlists.get(mlists.size() - 1).getTimestamp());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showContentView();
                sadapter.notifyDataSetChanged();
            }
        });
    }

    //加载更多
    public void loadMore(DongTaiSquareResponse dongListArray) {
        for (int i=0;i<dongListArray.getResult().size();i++){
        mlists.add(dongListArray.getResult().get(i));
        }

        //主动设置请求参数的时间戳
        mStatuRequest.setTimestamp(mlists.get(mlists.size() - 1).getTimestamp());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sadapter.notifyDataSetChanged();
            }
        });

    }
    /**
     * 注册评论状态的广播
     */
    public void registerCommentReceiver(){
        CommentReceiver.registerReceiver(this, new CommentReceiver.CommentChangeCallback() {
            @Override
            public void changCallback(CommentReceiver.CommentBean commentBean) {
                for (DongTaiSquareResponse.ResultBean bean :mlists) {
                    if(bean.getStatuId().equals(commentBean.getStatuId())){
                        //没有删除评论，所以所有的操作都是增加
                        bean.setCommentsSize(bean.getCommentsSize() + 1);
                        //避免没有必要的循环
                        break;
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       sadapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }
    /**
     * 发送动态成功后需要刷新当前界面
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == START_SEND_STATU_CODE) {
            switch (resultCode) {
                case PublishActivity.STATU_SEND_RESULT_CODE:
                    boolean b = data.getBooleanExtra(PublishActivity.STATU_SEND_RESULT_KEY, false);
                    if (b) {
                        getData();
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void initLocation(){

        //测试
        BaiDuLocationUtils.create(this, new BaiDuLocationUtils.OnLocationListener() {
            @Override
            public void onLocationSucced(BDLocation bdLocation, double latitude, double longitude) {
                Log.e(TAG, "定位成功啦，接受到定位数据" + latitude + "  " +longitude );
                updateLocation(bdLocation);
            }
        });
    }




    /**
     * 将位置信息发送给服务器
     * @param location
     */
    public void updateLocation(BDLocation location){
        //获取定位的结果，上传给服务器
        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        String userId = AppConfigUtils.getInstance().getLoginInfo(DongTaiSquareActivity.this).getObjectId();
        UpdateLocationRequest updateLocationRequest = new UpdateLocationRequest(userId,
                location.getLatitude(), location.getLongitude());

        Request request = RequestUtils.requestPOST(updateLocationRequest, Constant.URL.UPDATELOCATION);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i(TAG, "onResponse: " + result);
            }
        });
    }




//
//    private void getData(String userId,
//                         int limit,
//                         long timestamp,
//                         int filterType) {
//        OkHttpClient client = new OkHttpClient();
//        DongTaiList request0 = new DongTaiList(userId, limit, timestamp, filterType);
//        Gson gson = new Gson();
//        String json = gson.toJson(request0);
//        MediaType JSONTYPE = MediaType.parse("application/json;charset=utf-8");
//        RequestBody body = RequestBody.create(JSONTYPE, json);
//        final Request request = new Request.Builder()
//                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
//                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
//                .addHeader("Content-Type", "application/json")
//                .url("https://leancloud.cn:443/1.1/functions/getStatus")
//                .post(body)
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                Log.e(TAG, "onResponse: " + result);
//                DongTaiSquareResponse rr = new Gson().fromJson(result, DongTaiSquareResponse.class);
//                for (int i = 0; i < rr.getResult().size(); i++) {
//                    DongTaiListRequest r1 = new DongTaiListRequest(
//                            rr.getResult().get(i).getAuthor().getHeadProtrait(),
//                            rr.getResult().get(i).getAuthor().getUserId(),
//                            rr.getResult().get(i).getAuthor().getUserName(),
//                            rr.getResult().get(i).getCommentsSize(),
//                            rr.getResult().get(i).getImageUrls(),
//                            rr.getResult().get(i).getMessage(),
//                            rr.getResult().get(i).getPraiseSize(),
//                            rr.getResult().get(i).isPraiseStatus(),
//                            rr.getResult().get(i).getStatuId(),
//                            rr.getResult().get(i).getTimestamp()
//                    );
//                    dLists.add(r1);
//
//                }
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        sadapter.notifyDataSetChanged();
//                    }
//                });
//            }
//        });
//    }

    @OnClick(R.id.publish)
    public void onViewClicked() {
        Intent intent0 = new Intent(DongTaiSquareActivity.this, PublishActivity.class);
        startActivity(intent0);
    }
}

